package com.learn.mybtsp.service;

import com.learn.mybtsp.mapper.AdminUserMapper;
import com.learn.mybtsp.mapper.PermissionMapper;
import com.learn.mybtsp.mapper.RoleMapper;
import com.learn.mybtsp.security.MySimpleGrantedAuthority;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


@Service
@Slf4j
public class AuthService {

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        String requestURI = request.getRequestURI();
        log.info("访问的request URL:", requestURI);
        Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal)){
            //未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        for (GrantedAuthority authority : authorities) {

            MySimpleGrantedAuthority grantedAuthority = (MySimpleGrantedAuthority) authority;

            String[] paths = StringUtils.split(requestURI, "?");
            log.info(" 获取的权限数据： ",authority.getAuthority(), paths);
//            return  true;
            if (paths[0].equals(grantedAuthority.getPath())){
                return true;
            }
        }
        return false;
    }
}